package com.eduagent.xwqeduagent.api.DocumentTranslation.util;

import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Authentication utilities for document translation API
 */
public class AuthUtils {

    /**
     * Generate authentication parameters
     *
     * @param params Original parameters map
     * @param apiKey API key
     * @param appId Application ID
     * @return Map with authentication parameters added
     */
    public static TreeMap<String, Object> generateAuthParams(TreeMap<String, Object> params, String apiKey, String appId) {
        if (params == null) {
            params = new TreeMap<>();
        }
        
        // Add appId and timestamp
        params.put("appId", appId);
        params.put("apikey", apiKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        
        // Generate authentication string
        String authStr = generateAuthStr(params);
        
        // Remove API key (not needed in actual request) and add auth string
        params.remove("apikey");
        params.put("authStr", authStr);
        
        return params;
    }
    
    /**
     * Generate authentication string based on parameters
     *
     * @param params Parameters map including API key
     * @return MD5 hash of the parameters string
     */
    private static String generateAuthStr(Map<String, Object> params) {
        StringBuilder paramStr = new StringBuilder();
        Set<String> keys = params.keySet();
        boolean isFirst = true;
        
        for (String key : keys) {
            // Skip null values
            if (params.get(key) == null) {
                continue;
            }
            
            if (isFirst) {
                isFirst = false;
            } else {
                paramStr.append("&");
            }
            
            paramStr.append(key).append("=").append(params.get(key));
        }
        
        // Convert to MD5 hash
        return DigestUtils.md5DigestAsHex(paramStr.toString().getBytes());
    }
} 